package com.atguigu.distributed.lock.leecode;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Phone implements Runnable{
    public synchronized void sendMS() throws Exception{
        System.out.println(Thread.currentThread().getName()+"\t invoked sendMS()!");
        sendEMail();
    }
    public synchronized void sendEMail() throws Exception{
        System.out.println(Thread.currentThread().getName()+"\t invoked sendEMail()!");
    }
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        get();
    }


    public void get() {
        lock.lock();
        lock.lock();
        try{

            System.out.println(Thread.currentThread().getName()+"\t invoked get()!");
            set();
        }finally {
            lock.unlock();
        }
    }
    public void set(){
        try{
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"\t invoked set()!");
        }finally {
            lock.unlock();
        }
    }
}

public class ReentryLockDemo {
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(()->{
            try {
                phone.sendMS();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"t1").start();
        new Thread(()->{
            try {
                phone.sendMS();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"t2").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        Thread t3 = new Thread(phone, "t3");
        Thread t4 = new Thread(phone, "t4");
        t3.start();
        t4.start();
    }
}
